package cn.dgut.vinko.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.dgut.vinko.domain.Employee;

@WebFilter(filterName = "EmpLoginFilter", urlPatterns = "/")
public class EmpLoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("Filter Init..");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		// 获取session
		HttpSession httpSession = httpServletRequest.getSession();
		Employee employee = (Employee) httpSession.getAttribute("employee");

		// 没有用户登录
		if (employee == null) {
			httpServletResponse.sendRedirect("login.html");
		} else {
			chain.doFilter(httpServletRequest, httpServletResponse);
		}
	}

	@Override
	public void destroy() {
		System.out.println("Filter destroy..");
	}

}
